package com.qst.financing.service.serviceImpl;

import com.qst.financing.exception.MessageConstant;
import com.qst.financing.exception.PasswordErrorException;
import com.qst.financing.mapper.BankUserMapper;
import com.qst.financing.pojo.BankUser;
import com.qst.financing.mapper.BankUserMapper;
import com.qst.financing.pojo.DTO.BuserDTO;
import com.qst.financing.service.BankUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import com.qst.financing.exception.AccountNotFoundException;
import java.util.List;

@Service
public class BankUserServiceImpl implements BankUserService {
    @Autowired
    private BankUserMapper  bankUserMapper;

    @Value("${bank.bankid}")
    private Integer bankid;

    @Override
    public List<BankUser> selectAllBankUser(Integer bankid) {
        List<BankUser> bankUsers = bankUserMapper.selectAllBankUser(bankid);
        return bankUsers;
    }

    @Override
    public BankUser selectByUserName(String userName) {
        BankUser bankUser = bankUserMapper.selectByPrimaryKey(userName, bankid);
        return bankUser;
    }

    @Override
    public void update(BankUser bankUser) {
        bankUserMapper.updateByPrimaryKeySelective(bankUser);
    }

    @Override
    public void add(BankUser bankUser) {
        bankUserMapper.insertSelective(bankUser);
    }

    @Override
    public void delete(String userName) {
        bankUserMapper.deleteByPrimaryKey(userName);
    }
    @Override
    public BankUser login(BuserDTO userDTO){
        String username = userDTO.getUsername(); // 获取用户名
        String password = userDTO.getPassword(); // 获取密码

        // 1. 根据用户名查询数据库中的数据
        BankUser user = bankUserMapper.getByUsername(username);

        // 2. 处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        // 密码比对（MD5加密）
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }


        // 3. 返回员工实体对象
        return user;
    }
}
